package sige

import org.springframework.dao.DataIntegrityViolationException

class ContratoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {def lista = []
        params.max = Math.min(max ?: 10, 100)
        if( params.campo ){
            lista = Contrato.findById(Long.parselong("${params.campo}"))
        }else{
            lista = Contrato.list(params)
        }
        [contratoInstanceList: lista, contratoInstanceTotal: lista.size()]
    }

    def create(Long id) {
        def contratoInstance = new Contrato(params)
        contratoInstance?.anuidade = new DespesaVariavel(params)
        if(id){
            contratoInstance?.aluno = Aluno.get(id)
        }
        [contratoInstance: contratoInstance]
    }

    def save() {
        def contratoInstance = new Contrato(params)
        if (!contratoInstance.save(flush: true)) {
            render(view: "create", model: [contratoInstance: contratoInstance])
            return
        }
        Date mes = params.dataDeVencimento
        ContratoService cs = new ContratoService()
        cs.inserirRendimentos(contratoInstance)
        cs.inserirAnuidade(contratoInstance, mes)

        if(contratoInstance?.responsavel?.id){
            flash.message = message(code: 'default.created.message', args: [message(code: 'contrato.label', default: 'Contrato'), contratoInstance.id])
        }else{
            flash.message = message(code: 'contrato.criado.sem.responsave.message')
        }
        redirect(action: "show", id: contratoInstance.id)
    }

    def show(Long id) {
        def contratoInstance = Contrato.get(id)
        if (!contratoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "list")
            return
        }

        [contratoInstance: contratoInstance]
    }

    def edit(Long id) {
        def contratoInstance = Contrato.get(id)
        if (!contratoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "list")
            return
        }

        [contratoInstance: contratoInstance]
    }

    def update(Long id, Long version) {
        def contratoInstance = Contrato.get(id)
        if (!contratoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (contratoInstance.version > version) {
                contratoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'contrato.label', default: 'Contrato')] as Object[],
                          "Another user has updated this Contrato while you were editing")
                render(view: "edit", model: [contratoInstance: contratoInstance])
                return
            }
        }

        contratoInstance.properties = params

        if (!contratoInstance.save(flush: true)) {
            render(view: "edit", model: [contratoInstance: contratoInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'contrato.label', default: 'Contrato'), contratoInstance.id])
        redirect(action: "show", id: contratoInstance.id)
    }

    def delete(Long id) {
        def contratoInstance = Contrato.get(id)
        if (!contratoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "list")
            return
        }

        try {
            contratoInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "show", id: id)
        }
    }
    
    def emAtrazo(){
        def res = Contrato.withCriteria {
            def hoje = new Date()
            anuidade{
                pagamentos{
                    lt('dataDeVencimento', hoje)
                    isNull("dataDePagamento")
                }
            }
        }
        
        [contratoInstanceList: res, contratoInstanceTotal: res.size()]
    }
    
    def imprime(Long id) {
        def contratoInstance = Contrato.get(id)
        if (!contratoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'contrato.label', default: 'Contrato'), id])
            redirect(action: "list")
            return
        }

        [contratoInstance: contratoInstance]
    }

    
    def updateTurmas = {
        def turmas
        try{
            println("updateTurmas: $params")
            long id = Long.parseLong(params.id)
            def ano =  AnoLetivo.get(id)
            turmas = ano?.turmas
            println "$turmas"
        }catch (e){
            println e
        }
        render (template: 'selectTurma', model:[turmaList: turmas, 
                messageCode: 'turma.label' ])
    }
    
    def opcaoResp = {
        println params
        if(params.op == "1"){
            render (template: 'digitaCpf')
        }else{
            render " "
        }
    }
    
    def updateResponsaveis = {
       def responsavel = Responsavel.findByCpfLike("%${params.value}%")
       
       render (template: 'selectResponsavel', model:[responsavelInstance: responsavel, 
                messageCode: 'contrato.responsavel.label' ])
    }
    
    def updateTable = {
        def lista = Contrato.findById(Long.parselong("${params.value}"))
        
        render (template: 'table', model:[contratoInstanceList: lista, 
            contratoInstanceTotal: lista.size()])
    }
}
